import React, { Component } from 'react';
import { Modal, Tabs, Dropdown, Menu, message } from 'antd';
import s from './index.module.less';
import { renderEmpty } from '../../common/commonRender';
import InfoStageTabInfo from './infoStageTabInfo';
import ProjectMember from '../projectMember';
import ProjectMaterial from '.././projectMaterial';
import ProjectTask from '../projectTask';

const TabPane = Tabs.TabPane;
const confirm = Modal.confirm;
function showConfirm({ title, content, onOk }) {
    confirm({
        okText: '确定',
        cancelText: '取消',
        title,
        content,
        onOk,
    });
}

export function canSaveStage(stage, projecttype) {
    const { title, phone, name, rectype, contact, members } = stage.info.client[0];
    if ((projecttype === 1 || projecttype === 2) && !title) {
        message.warn('委托人身份不能为空');
        return false;
    }
    if (!name) {
        message.warn(`委托人${rectype ? '姓名' : '名称'}不能为空`);
        return false;
    }
    if (!phone) {
        message.warn('委托人联系电话不能为空');
        return false;
    }
    if (!rectype && !contact) {
        message.warn('委托人的联系人不能为空');
        return false;
    }
    if (!members.length || !members.some(v => v.innergrouptype === 1)) {
        message.warn('请选择委托人组成员再确认保存');
        return false;
    }
    return true;
}

class InfoStageTab extends Component {

    // 不可修改，父组件要通过getValue()获取值
    getValue = () => {
        const { stages } = this.props.detailData;
        const data = stages.reduce((pre, v, i) => {
            if (this[`stage${i}`]) {
                const stage = this.getValueByIndex(i);
                return pre.concat(stage);
            };
            return pre
        }, []);
        // console.log('--InfoStageTab--', data);
        return data;
    }

    getValueByIndex = (index) => {
        const stage = JSON.parse(JSON.stringify(this[`stage${index}`].getValue()));
        delete stage.isNewStage;
        // 再获取成员的值
        const { outerMembers, innerMembers } = this[`member${index}`].getValue();
        stage.members = outerMembers;
        stage.info.client[0].members = innerMembers;
        return stage;
    }

    renderTab(stage, i) {
        const { create, isBoss, detailData } = this.props;
        const { iscomplete: pIsComplete } = detailData;
        return (
            <div className={s.stageTabLable}>
                {stage.iscomplete ? <span className="mdi mdi-checkbox-marked-circle" /> : null}
                {stage.name}
                {(create || isBoss) && !pIsComplete ? (
                    <Dropdown overlay={this.renderTabMenu(stage, i, stage.iscomplete)}>
                        <span className="mdi mdi-menu-down" />
                    </Dropdown>
                ) : null}
            </div>
        )
    }

    renderTabMenu(v, i, iscomplete) {
        const { create } = this.props;
        return (
            <Menu onClick={e => this.handelStage(e, v, i)}>
                {!iscomplete && !create ? <Menu.Item key="completeStage">完成阶段</Menu.Item> : null}
                {iscomplete && !create ? <Menu.Item key="restartStage">重启阶段</Menu.Item> : null}
                {create ? <Menu.Item key="deleteStage">删除阶段</Menu.Item> : null}
            </Menu>
        );
    }

    handelStage = ({ domEvent, key }, v, i) => {
        domEvent.stopPropagation();
        domEvent.preventDefault();
        this[key](v, i, key);
    }

    completeStage = (v, i, key) => {
        const { detailData: { projectid }, projectState: { manageProject } } = this.props;
        showConfirm({
            title: '确定完成当前阶段?',
            content: '请确保当前阶段的所有流程或者任务都已完成，设置为完成之后当前阶段所有信息将不可被编辑',
            onOk: () => {
                manageProject({
                    key,
                    index: i,
                    value: true,
                    params: { projectid, stageid: v.stageid }
                }, () => {
                    message.success('设置完成成功');
                    this.handelCompleteAndRestart(true, i);
                });
            },
        })
    }

    restartStage = (v, i, key) => {
        const { detailData: { projectid }, projectState: { manageProject } } = this.props;
        showConfirm({
            title: '确定重启当前阶段?',
            onOk: () => {
                manageProject({
                    key,
                    index: i,
                    value: false,
                    params: { projectid, stageid: v.stageid }
                }, () => {
                    message.success('重启成功');
                    this.handelCompleteAndRestart(false, i);
                });
            },
        })
    }

    handelCompleteAndRestart = (iscomplete, i) => {
        const { detailData, onStagesChange } = this.props;
        const { stages } = detailData;
        const newStages = stages.concat();
        const stage = JSON.parse(JSON.stringify(newStages[i]));
        stage.iscomplete = iscomplete;
        newStages[i] = stage;
        // 更新state
        onStagesChange({ stages: newStages });
    }

    deleteStage = (v, i) => {
        if (!this.props.create) {
            const { detailData: { projectid }, projectState: { deleteStage } } = this.props;
            deleteStage({ projectid, stageid: v.stageid }, () => {
                this.handleDeleteStage(i);
            });
        } else this.handleDeleteStage(i);
    }

    handleDeleteStage = (i) => {
        const { detailData, onStagesChange, activeIndex } = this.props;
        const { stages } = detailData;
        const newArr = [
            ...stages.slice(0, i),
            ...stages.slice(i + 1),
        ];

        const setData = { stages: newArr, activeIndex };
        if (activeIndex === String(i) && i === newArr.length) {
            // 删除当前项，并且为原数组最后一项，默认激活前一项
            setData.activeIndex = `${i - 1}`;
        } else if (activeIndex === String(i)) {
            // 删除当前项，无论是不是第一项，都默认激活后一项，此时activeIndex是不变的，要强制刷新
            setData.reflesh = true;
        } else if (activeIndex > i) {
            // 删除激活状态前面的值
            setData.activeIndex = `${activeIndex - 1}`;
        }
        onStagesChange(setData);
    }

    tabChange = (key) => {
        const {
            detailData: { stages },
            onStagesChange
        } = this.props;

        onStagesChange({ stages, activeIndex: key });
    }

    isLawyer = (stage) => { // 律师协作团队成员
        if (!stage) return false;
        const { islawyermember, islawyermanager, islawyerhost } = stage;
        return islawyermember || islawyermanager || islawyerhost;
    }

    onSaveNewStage = (i) => {
        const stage = this.getValueByIndex(i);
        const {
            activeIndex,
            onStagesChange,
            detailData: { stages, projecttype, projectid },
            projectState: { addStage }
        } = this.props;
        const canSave = canSaveStage(stage, projecttype);
        if (!canSave) return;
        addStage({ projectid, projecttype, stages: [stage] }, () => {
            message.success('添加项目阶段成功');
            const newStages = stages.concat();
            newStages.pop();
            onStagesChange({ stages: [...newStages, ...[stage]], activeIndex });
        });
    }

    render() {
        const { create, isBoss, detailData, userState, activeIndex, commonState, projectState } = this.props;
        const { stages } = detailData;

        return (
            <div className={s.content}>
                {stages.length ? (
                    <Tabs activeKey={activeIndex} onChange={this.tabChange}>
                        {stages.map((stage, i) => (
                            <TabPane
                                key={i}
                                tab={this.renderTab(stage, i)}
                            >
                                {!create && !stage.ismember ? renderEmpty('你不属于当前阶段的成员') : (
                                    <div className={s.wrapStage}>
                                        {
                                            !create && stage.isNewStage ?
                                                <span onClick={() => this.onSaveNewStage(i)} className={s.saveNewStage}>保存</span> : null
                                        }
                                        <InfoStageTabInfo
                                            ref={d => this[`stage${i}`] = d}
                                            stage={stage}
                                            create={create || stage.isNewStage}
                                            isLawyer={this.isLawyer(stage)}
                                            detailData={{ ...detailData, stages }}
                                            userState={userState}
                                            projectState={projectState}
                                            infoField={projectState.infoField}
                                            identities={projectState.identities}
                                        />
                                        <ProjectMaterial
                                            data={stage}
                                            col={1}
                                            create={create}
                                            isBoss={isBoss}
                                            isLawyer={this.isLawyer(stage)}
                                            detailData={detailData}
                                            projectState={projectState}
                                        />
                                        <ProjectTask
                                            data={stage}
                                            create={create}
                                            commonState={commonState}
                                            projectState={projectState}
                                        />
                                        <ProjectMember
                                            ref={d => this[`member${i}`] = d}
                                            data={stage}
                                            create={create}
                                            info={userState.info}
                                            projectState={projectState}
                                        />
                                    </div>
                                )}
                            </TabPane>
                        ))}
                    </Tabs>
                ) : renderEmpty('请添加项目阶段')}
            </div>
        );
    }
}

export default InfoStageTab